#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
import time
import datetime
import hashlib
import functools
import tempfile

import math
import subprocess

from util.logger import process_log


def parse_delta(cond):
    unit_map = {
        'day': 24 * 60 * 60,
        'hour': 60 * 60,
        'minute': 60,
        'second': 1,
    }
    value, unit = cond.split('-')
    return int(value) * unit_map[unit]


def calculate_date_day(date, fmt, delta):
    if not date:
        return ''
    date = date.strip(' ')
    seconds = parse_delta(delta)
    delta = datetime.timedelta(seconds=seconds)
    before = datetime.datetime.strptime(date, fmt) - delta
    return before.strftime('%Y-%m-%d %H:%M:%S')


def format_date(date):
    if type(date) is datetime.datetime:
        return str(date)
    date = str(date)
    dt = None
    for dt_format in ["%Y-%m-%d %H:%M:%S", "%Y-%m-%d", "%Y %m", "%Y", "%d-%m-%Y", "%m-%d-%Y"]:
        try:
            date = datetime.datetime.strptime(str(date), '%Y-%m-%d')
        except Exception:
            pass
        try:
            dt = datetime.datetime.strptime(date, dt_format)
        except Exception:
            pass
    if dt is None:
        return date
    else:
        return str(dt)


def get_md5(content):
    md5_obj = hashlib.md5()
    md5_obj.update(content)
    return md5_obj.hexdigest()


def row2str(row):
    temp_row = []
    for r in row:
        if None == r:
            temp_row.append('')
        else:
            temp_row.append(str(r))
    return temp_row


def one_instance(func):
    @functools.wraps(func)
    def f(*args, **kwargs):
        import sys
        basename = os.path.splitext(os.path.abspath(sys.argv[0]))[0].replace(
            "/", "-").replace(":", "").replace("\\", "-") + '-%s' % '' + '.lock'
        lockfile = os.path.normpath(
            tempfile.gettempdir() + '/' + basename)

        if sys.platform == 'win32':
            try:
                if os.path.exists(lockfile):
                    os.unlink(lockfile)
                fd = os.open(
                    lockfile, os.O_CREAT | os.O_EXCL | os.O_RDWR)
            except OSError:
                type, e, tb = sys.exc_info()
                if e.errno == 13:
                    process_log().error(
                        "Another instance is already running, quitting.")
                    sys.exit(-1)
                print(e.errno)
                raise
            process_log().info(
                "processing begin")
            func(*args, **kwargs)
            process_log().info(
                "processing finished")
            try:
                os.close(fd)
            except:
                pass
        else:  # non Windows
            import fcntl
            fp = open(lockfile, 'w')
            try:
                fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
            except IOError:
                fp.close()
                process_log().info(
                    "Another instance is already running, quitting.")
                sys.exit(-1)
            func(*args, **kwargs)
            try:
                fp.close()
            except:
                pass

    return f


def byte_format(size, unit='Bytes'):
    units = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB']
    return ('%.2f' + " " + unit) % (size / math.pow(1024, units.index(unit)))


def get_task_name(dir):
    """
    get the task name by start with the param dir.
    return the list of task name.
    """
    schtask = 'schtasks'
    subprocess.Popen(['cmd', '/c', 'chcp 437'])
    res = subprocess.Popen(['cmd', '/c', schtask], stdout=subprocess.PIPE)
    schema = ['folder', 'title', 'div', 'task', 'blank']
    index = 0
    task_name = []
    dir = dir.replace('C:', '')
    for line in iter(res.stdout.readline, b''):
        content = str(line)
        if content.find('Folder') == 0:
            index = 0
        elif index < 3:
            index += 1
        elif len(content) <= 2:
            index = 4
        if schema[index] == 'folder':
            folder = content.split(': ')[-1]
            print '==============', folder
        elif schema[index] == 'div':
            div = content.find(' ')
        elif schema[index] == 'task':
            task = content[0:div]
            while task.endswith(' '):
                task = task[0:-2]
            if folder.find(dir) != -1:
                task_name.append(task)
    res.communicate()
    return task_name


def get_db_tb_key(db, tb):
    return ('%s+++%s' % (db, tb)).lower()


def is_binlog(file_name):
    try:
        with open(file_name, 'rb') as rb:
            bytes_4 = rb.read(4)
            hexstr = "%s" % bytes_4.encode('hex')
            if hexstr == 'fe62696e':
                return True
    except Exception as e:
        process_log().warn(e)
        return False
    return False


def bytearray_to_hex(bs):
    """Convert bytearray to hex string

    Given a bytearray, convert it to a string of
    an even length, containing the associated
    hexadecimal characters for each byte

    Args:
        bs:
    """
    try:
        hs = ["{0:0>2}".format(hex(b)[2:].upper()) for b in bs]
        return '0x' + ''.join(hs)
    except:
        return bs


